# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from common.models import Location
from django.db.models import Q
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt

import Geohash
import mzgeohash
import json
import os
import requests

from wechat.official import WxApplication, WxTextResponse

from .models import User_WX,User_Agent,User_Customer
from common.models import Splashes
from wx_insurance.settings import BASE_DIR
from common.models import WxApp

timeout=1000
worker_session = requests.Session()

wx_app = WxApp.objects.get(id=1)
APP_SECRET = wx_app.app_secret
SECRET_TOKEN = wx_app.secret_token
APP_ID = wx_app.app_id
ENCODING_AES_KEY = wx_app.encoding_aes_key
SPLASH_RANDOM = wx_app.splash_random
if SPLASH_RANDOM:
    SPLASH_DEFAULT = 0
else:
    SPLASH_DEFAULT = int(wx_app.splash_default) - 1
    if SPLASH_DEFAULT < 0 :
        SPLASH_DEFAULT = 0

# APP_SECRET = "1"
# SECRET_TOKEN ="1"
# APP_ID = "1"
# ENCODING_AES_KEY = "1"
# SPLASH_RANDOM = "1"
# SPLASH_DEFAULT = 0

def splash(request):
    response_data = dict()
    response_data["status"] = False
    try:
        splashes = Splashes.objects.all().filter(status="100")
        if SPLASH_RANDOM:
            from random import choice
            splash_content = str(choice(splashes).content)
        else:
            splash_content = str(splashes[SPLASH_DEFAULT].content)
        response_data["status"] = True
        response_data["default"] = SPLASH_DEFAULT
        response_data["random"] = SPLASH_RANDOM
        response_data["url"] = splash_content
    except Exception as e:
        response_data["reason"] = "{0}" .format(e)
    return HttpResponse(json.dumps(response_data))

def login(request):
    """微信用户登陆
    输入：request[openid]
    输出：用户类型
    """
    info = dict()
    info['status'] = False
    info['type'] = 0
    try:
        openid = request.GET['openid']
        userInfo = request.GET['userInfo']
        user_wx = User_WX.objects.filter(wx_openid=openid)
        if not user_wx:
            new_user_openid = new_wx_user(openid,userInfo)
            if new_user_openid <> 0 :
                info['status'] = True
                info['openid'] = new_user_openid
        else:
            info['status'] = True
            info['openid'] = user_wx[0].wx_openid
            info['type'] = user_wx[0].type
    except Exception as e:
        print('User login with openid error :{0} '.format(e))
    return HttpResponse(json.dumps(info))

def new_wx_user(openid,user_info):
    """微信用户信息信息保存
    输入：request[openid、user_info]
    输出：微信对象openid
    """
    user_info = eval(user_info)
    print(openid,
          user_info['gender'],
          user_info['nickName'],
          user_info['avatarUrl'],
          user_info['language'],
          user_info['country'],
          user_info['province'],
          user_info['city'],)

    try:
        user_wx = User_WX(
            wx_openid = openid,
            wx_gender = int(user_info['gender']),
            wx_nickname = user_info['nickName'],
            wx_avatarUrl = user_info['avatarUrl'],
            wx_language = user_info['language'],
            wx_country = user_info['country'],
            wx_province = user_info['province'],
            wx_city = user_info['city'],
            type = 0
        )
        user_wx.save()
        return user_wx.wx_openid
    except Exception as e:
        print(e)
        return 0

def save_wx_location_info(lnt,lat,acc):
    """微信的GPS格式的位置信息保存
    输入：request[lnt,lat,acc（精度）]
    输出：Location对象的ID
    """
    upload_result = dict()
    upload_result["result"] = False
    print(Geohash.encode(float(lat), float(lnt), 16))
    try:
        new_location = Location(
            latitude = lat,
            longitude = lnt,
            precision = acc,
            geohash = Geohash.encode(float(lat),float(lnt),16)
        )
        new_location.save()
        return new_location
    except Exception as e:
        print(e)
        return None

@csrf_exempt
def upload_photo(request,**kwargs):
    """用户照片上传
    输入：request[file]
    输出：照片路径
    """
    staticFolder = 'static'
    fileType = 'user_photo'
    subFolder = request.POST['openid']
    defaultFilename = 'photo.jpg'
    upload_result = dict()
    upload_result["result"] = False
    try:
        #只保留唯一文件
        destinate_img_dir_path = os.path.join(BASE_DIR,staticFolder,fileType,subFolder)
        destinate_img_file_path = os.path.join(destinate_img_dir_path, defaultFilename)
    except Exception as e:
        print("upload_photo fuction get path error for {0}".format(e))
        return HttpResponse(json.dumps(upload_result))

    print(destinate_img_dir_path,os.path.exists(destinate_img_dir_path))

    if os.path.exists(destinate_img_dir_path) is False:
        try:
            os.mkdir(destinate_img_dir_path)
        except Exception as e:
            print("upload_photo fuction os.mkdir error for {0}" .format(e))
            return HttpResponse(json.dumps(upload_result))
    else:
        print("文件夹已存在，直接保存")
        pass

    with open(destinate_img_file_path, 'wb') as f:
        f.write(request.FILES[fileType].read())
        f.close
        upload_result["result"] = True
        upload_result["image_url"] = r"static/" + fileType + r"/" + subFolder + r"/"  + defaultFilename

    return HttpResponse(json.dumps(upload_result))

@csrf_exempt
def register(request):
    """用户注册。
    输入：request[openid、userType（注册用户类型，由用户自行选择）、formDara（具体的表单信息）]
    输出：注册结果
    """
    register_result = dict()
    register_result["result"] = False
    register_result["hint"] = "Input Data Error!"
    try:
        userType = request.GET['userType']
        userOpenID = request.GET['openid']
        if not userType or not userOpenID or userOpenID == "":
            register_result["hint"] = "Input Data Error : {0}!".format("No value")
            return HttpResponse(json.dumps(register_result))
    except Exception as e:
        print(e)
        register_result["hint"] = "Input Data Error : {0}!" .format(e)
        return HttpResponse(json.dumps(register_result))


    lnt = None
    lat = None
    acc = None
    try:
        lnt = request.GET['lnt']
        lat = request.GET['lat']
        acc =request.GET['acc']
    except Exception as e:
        register_result["hint"] = "Input Data Error : {0}!" .format(e)
        pass

    if userType == '10':
        try:
            name = request.GET['username']
            gender = request.GET['gender']
            mobile = request.GET['mobile']
            if not name or not gender or not mobile:
                print("Input Data Error : {0}!".format("No name or gender or mobile"))
                register_result["hint"] = "Input Data Error : {0}!".format("No name or gender or mobile")
                return HttpResponse(json.dumps(register_result))
        except Exception as e:
            print("Input Data Error : {0}!".format(e))
            register_result["hint"] = "Input Data Error : {0}!".format(e)
            return HttpResponse(json.dumps(register_result))

        requirements = request.GET['reqContent']
        if not requirements:
            requirements = "无具体需求"

        requireType = request.GET['reqType']
        if not requireType:
            requireType = "我要投保"

        contact_allow = 0
        if request.GET['contactAllowed']:
            contact_allow = 1

        user_wx = User_WX.objects.get(wx_openid = userOpenID)
        if lnt and lat and acc:
            if lnt <>"0" and lat<>"0" and acc<>"0":
                user_wx.location =  save_wx_location_info(lnt,lat,acc)
                user_wx.save()

        user_customer = User_Customer(
                            user_wx=user_wx,
                            name = name,
                            gender = gender,# help_text="0：保密，100：女，99：男"
                            mobile = mobile,
                            requirements = requirements,
                            requireType = requireType,
                            contact_allow = contact_allow
                        )
        user_customer.save()
        register_result["result"] = True
        return HttpResponse(json.dumps(register_result))
    elif userType == '20':
        try:
            name = request.GET['username']
            gender = request.GET['gender']
            mobile = request.GET['mobile']
            company = request.GET['company']
            photo = request.GET['userPhoto']
            if not name or not gender or not mobile or not company or not photo:
                print("Input Data Error : {0}!".format("No name or gender or mobile or company or photo"))
                register_result["hint"] = "Input Data Error : {0}!".format("No name or gender or mobile or company or photo")
                return HttpResponse(json.dumps(register_result))
        except Exception as e:
            print("Input Data Error : {0}!".format(e))
            register_result["hint"] = "Input Data Error : {0}!".format(e)
            return HttpResponse(json.dumps(register_result))

        in_career = request.GET['in_career']
        if not in_career:
            in_career = 0

        certificate_no = request.GET['certificate_no']
        if not certificate_no:
            certificate_no = "暂无"

        self_introduction = request.GET['introContent']
        if not self_introduction:
            self_introduction = "暂无"

        user_wx = User_WX.objects.get(wx_openid=userOpenID)
        if lnt and lat:
            user_wx.location = save_wx_location_info(lnt, lat, acc)
            user_wx.save()

        user_agent = User_Agent(
            user_wx=user_wx,
            name=name,
            gender=gender,  # help_text="0：保密，100：女，99：男"
            mobile=mobile,
            company=company,
            photo = photo,
            in_career = in_career,
            certificate_no = certificate_no,
            self_introduction = self_introduction,
        )
        user_agent.save()
        register_result["result"] = True
        return HttpResponse(json.dumps(register_result))
    else:
        print("Input Data Error : {0}!".format("UserType Err"))
        register_result["hint"] = "Input Data Error : {0}!".format("UserType Err")
        return HttpResponse(json.dumps(register_result))

def contact_info(request):
    """根据当前用户的类型与目标用户的ID返回特定的用户信息内容给请求者。
    输入：request[current_user_type（当前用户类型）、target_user_id（目标用户的ID）]
    输出：用于地图Mask和进一步展示给用户的图片信息
    """
    info_result = dict()
    info_result["result"] = False
    user_id = request.GET['target_user_id']
    current_user_type = request.GET['current_user_type']

    contact_info = dict()
    contact_info_exsit = False
    if current_user_type == '10':
        print("Contact Info : {0},{1}" .format(current_user_type,user_id))
        user_agent = User_Agent.objects.filter(user_wx__id=user_id)
        if user_agent:
            user_agent = user_agent[0]
            contact_info["type"] = 20
            contact_info["name"] = user_agent.name
            contact_info["gender"] = user_agent.gender
            contact_info["mobile"] = user_agent.mobile
            contact_info["company"] = user_agent.company
            contact_info["photo"] = user_agent.photo
            contact_info["in_career"] = user_agent.in_career
            contact_info["certificate_no"] = user_agent.certificate_no
            contact_info["self_introduction"] = user_agent.self_introduction
            info_result["info"] = contact_info
            contact_info_exsit = True
            info_result["result"] = True

    elif current_user_type == '20':
        user_customer = User_Customer.objects.filter(user_wx__id=user_id)
        if user_customer:
            user_customer = user_customer[0]
            contact_info["type"] = 10
            contact_info["name"] = user_customer.name
            contact_info["gender"] = user_customer.gender
            contact_info["mobile"] = user_customer.mobile
            contact_info["requireType"] = user_customer.requireType
            contact_info["requirements"] = user_customer.requirements
            contact_info["contact_allow"] = user_customer.contact_allow
            info_result["info"] = contact_info
            contact_info_exsit = True
            info_result["result"] = True

    if not contact_info_exsit:
        print("No user information with ID {0}".format(user_id))
        info_result["hint"] = "No user information with ID {0}".format(user_id)
    return HttpResponse(json.dumps(info_result))

def local_info(request):
    """根据用户类型、当前的位置以及地图倍率进行信息查询。
    输入：request[current_user_type（当前用户类型）、location_lng（当前LNT）、location_lat（当前LAT）、scale_ranger（放大倍数）]
    输出：用于地图Mask和进一步展示给用户的图片信息
    """
    info_result = dict()
    info_result["result"] = False

    try:
        current_user_type = request.GET['current_user_type']
        location_lng = request.GET['location_lng']
        location_lat = request.GET['location_lat']
        scale_ranger = request.GET['scale_ranger']
    except Exception as e:
        print("Get Local Info Error :{0}" .format(e))
        return HttpResponse(json.dumps(info_result))

    target_ranger_int = 16
    if scale_ranger :
        if scale_ranger <>"0":
            target_ranger_int = int(scale_ranger)

    if current_user_type == "0" or current_user_type == 0:
        current_user_type = "10"
    else:
        current_user_type = str(current_user_type)

    # 寻找九宫格
    print("function local info with location_lat {0} scale {1}" .format(location_lat,target_ranger_int))
    if location_lat=="0" or location_lng =="0":
        current_user_location = Geohash.encode(31.230416,121.473701,16)
    else:
        current_user_location = Geohash.encode(float(location_lng),float(location_lat),target_ranger_int)

    current_user_location_neighbors = mzgeohash.neighbors(current_user_location[:target_ranger_int-4])
    current_user_location_neighbors_hash = []
    for step in  ['c','e','n','ne','nw','s','se','sw','w']:
        current_user_location_neighbors_hash.append(current_user_location_neighbors[step])
    print(current_user_location,current_user_location_neighbors_hash,current_user_type)

    user_lists = []
    for hash in current_user_location_neighbors_hash:
        print(hash)
        if current_user_type == "10":
            user_agent_lists = User_Agent.objects.filter(user_wx__location__geohash__startswith=hash)
            if user_agent_lists:
                print(user_agent_lists)
                for user_agent in user_agent_lists:
                    data1 = dict()
                    data1['id'] = user_agent.user_wx.id
                    data1['latitude'] = float(user_agent.user_wx.location.latitude)
                    data1['longitude'] = float(user_agent.user_wx.location.longitude)
                    data1['iconPath'] = "/images/icon_people.png"
                    data1['rotate'] = 0
                    data1['callout'] = dict()
                    data1['callout']['content'] = user_agent.name + "," + user_agent.self_introduction
                    # data1['callout']['color'] = ""
                    # data1['callout']['fontSize'] = ""
                    # data1['callout']['borderRadius'] = ""
                    data1['callout']['bgColor'] = "#FFFFFF"
                    # data1['callout']['padding'] = ""
                    # data1['callout']['boxShadow'] = ""
                    # data1['callout']['display'] = "BYCLICK"
                    data1['callout']['display'] = "ALWAYS"
                    user_lists.append(data1)
            else:
                pass
        elif current_user_type == "20":
            user_customer_lists = User_Customer.objects.filter(user_wx__location__geohash__startswith=hash)
            print("Check out customer")
            if user_customer_lists:
                print(user_customer_lists)
                for user_customer in user_customer_lists:
                    data1 = dict()
                    data1['id'] = user_customer.user_wx.id
                    data1['latitude'] = float(user_customer.user_wx.location.latitude)
                    data1['longitude'] = float(user_customer.user_wx.location.longitude)
                    data1['iconPath'] = "/images/icon_location.png"
                    data1['rotate'] = 0
                    data1['callout'] = dict()
                    data1['callout']['content'] = user_customer.name + "," + user_customer.requirements
                    # data1['callout']['color'] = ""
                    # data1['callout']['fontSize'] = ""
                    # data1['callout']['borderRadius'] = ""
                    data1['callout']['bgColor'] = "#FFFFFF"
                    # data1['callout']['padding'] = ""
                    # data1['callout']['boxShadow'] = ""
                    # data1['callout']['display'] = "BYCLICK"
                    data1['callout']['display'] = "ALWAYS"
                    user_lists.append(data1)
            else:
                pass
    if len(user_lists) > 0:
        info_result["result"] = True
        info_result["data"] = user_lists
    print(info_result)
    return HttpResponse(json.dumps(info_result))

class WxApp(WxApplication):
    def __init__(self):
        self.APP_SECRET = APP_SECRET
        self.SECRET_TOKEN = SECRET_TOKEN
        self.APP_ID = APP_ID
        self.ENCODING_AES_KEY = ENCODING_AES_KEY

    def on_text(self, req):
        """把用户输入的文本原样返回。
        输入：加密过的Token
        输出：Token原文
        """
        print(req.Content, req)
        text_content = WxTextResponse(req.Content, req)
        return text_content

@csrf_exempt
def wechat(request):
    """验证微信的Token请求
    输入：加密过的Token
    输出：Token原文
    """
    app = WxApp()
    result = app.process(request.GET, request.body)
    #print("Wechat app process result :{0}" .format(result))
    return HttpResponse(result)

def get_openid(request):
    """获取用户openid
    输入：request[js_code、user_info]
    输出：json[openid、expires_in、session_key]
    """
    jsdata= dict()
    user_info = dict()
    js_code = request.GET['js_code']
    # try:
    #     # user_info["province"] = request.GET['province']
    #     # user_info["city"] = request.GET['city']
    #     # user_info["language"] = request.GET['language']
    #     # user_info["avatarUrl"] = request.GET['avatarUrl']
    #     # user_info["gender"] = request.GET['gender']
    #     # user_info["country"] = request.GET['country']
    #     # user_info["nickName"] = request.GET['nickName']
    #     for info in request.GET:
    #         user_info[user_info] = request.GET[info]
    # except Exception as e:
    #     print ("Get Openid Function Err with get request content: {1}" .format(e))
    #     return HttpResponse(json.dumps(jsdata))
    #
    # print(user_info)

    request_url = 'https://api.weixin.qq.com/sns/jscode2session?appid='+APP_ID+'&secret='+APP_SECRET+'&grant_type=authorization_code&js_code='+js_code
    headers = { 'content-type': 'application/json'}
    result = worker_session.get(request_url, stream=True, headers=headers)#, timeout=1000)

    if result:
        print(result.status_code)
        if result.status_code <> 200:
            jsdata['errcode'] = result.status_code
        else:
            jsdata = json.loads(result.content)
            try:
                openid = jsdata['openid']
                expires_in = jsdata['expires_in']
                session_key = jsdata['session_key']
                jsdata['errcode'] = 0
            except Exception as e:
                print ("Get Openid Function Err {0}, {1}" .format(jsdata,e))
        return HttpResponse(json.dumps(jsdata))
    else:
        return HttpResponse(json.dumps(jsdata))

